package com.example.arithmeticleetcode.learnArithmetic.stack;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * @program: arithmetic-leetcode
 * @description: 左右括号匹配
 * @author: FangZhen
 * @create: 2020-08-20 15:33
 **/
public class StackExercise02 {

    /**
     * 栈
     *
     * @param s
     * @return
     */
    public boolean isValid03(String s) {
        Map<Character, Character> map = new HashMap<>();
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');
        int length = s.length();
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (map.containsKey(c)) {
                stack.push(c);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                Character left = stack.pop();
                if (c != map.get(left)) return false;
            }
        }
        return stack.isEmpty();
    }


    /**
     * 栈
     *
     * @param s
     * @return
     */
    public boolean isValid02(String s) {

        Stack<Character> stack = new Stack<>();
        int length = s.length();
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (c == '[' || c == '{' || c == '(') {
                stack.push(c);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                Character left = stack.pop();
                if (left == '(' && c != ')') return false;
                if (left == '[' && c != ']') return false;
                if (left == '{' && c != '}') return false;
            }
        }
        return stack.isEmpty();
    }


    /**
     * 传统
     *
     * @param s
     * @return
     */
    public boolean isValid(String s) {
        while (s.contains("{}") || s.contains("[]") || s.contains("()")) {
            s = s.replace("{}", "");
            s = s.replace("()", "");
            s = s.replace("[]", "");
        }
        return s.isEmpty();
    }
}
